package com.reformer.commons.utils;

import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@SuppressWarnings({"rawtypes", "unchecked"})
public class CglibUtil {

    public static Object getValue(Object obj, String key) {
        BeanMap map = BeanMap.create(obj);
        return map.get(key);
    }

    public static void setValue(Object obj, String key, Object value) {
        BeanMap map = BeanMap.create(obj);
        if (map.containsKey(key)) {
            map.put(key, value);
        }

    }

    public static void setValue(Object obj, Map<String, Object> map) {
        BeanMap beanmap = BeanMap.create(obj);
        for (String key : map.keySet()) {
            if (beanmap.containsKey(key)) {
                beanmap.put(key, map.get(key));
            }
        }
    }

    public static Map copyToMap(Object obj) {
        HashMap map = new HashMap();
        BeanMap beanMap = BeanMap.create(obj);
        Set keys = beanMap.keySet();
        for (Object key : keys) {
            Object value = beanMap.get(key);
            if (value != null) {
                map.put(key, value);
            }
        }
        return map;
    }

    public static boolean objFieldIsAllNull(Object obj) {
        BeanMap beanMap = BeanMap.create(obj);
        Set keys = beanMap.keySet();
        for (Object key : keys) {
            Object value = beanMap.get(key);
            if (value != null) {
                return false;
            }
        }
        return true;
    }
}
